package com.sx.zongzhi.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.zongzhi.R;
import com.sx.zongzhi.activity.EducationActivity;
import com.sx.zongzhi.adapter.SpinnerPubAdapter;
import com.sx.zongzhi.bean.EducationBean;
import com.sx.zongzhi.bean.GlobalBean;
import com.sx.zongzhi.bean.PopulationDetailBean;
import com.sx.zongzhi.bean.ProvinceBean;
import com.sx.zongzhi.bean.PublicBean;
import com.sx.zongzhi.net.ServiceFactory;
import com.sx.zongzhi.presenter.CheckMessagePest;
import com.sx.zongzhi.presenter.PublicListPest;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.ProvinceUtils;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.ICheckMessageView;
import com.sx.zongzhi.view.IPublicBeanView;
import com.sx.zongzhi.widget.LoadDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * Created by XZY on 2017/11/28.
 * 基本信息添加或编辑
 */
public class BasicInforEditFragment extends Fragment implements IPublicBeanView,ICheckMessageView{

    @BindView(R.id.imv_Head) ImageView imv_Head;
    @BindView(R.id.et_IDCard) EditText et_IDCard;
    @BindView(R.id.et_Name) EditText et_Name;
    @BindView(R.id.sp_Sex) Spinner sp_Sex;
    @BindView(R.id.tv_Data) TextView tv_Data;
    @BindView(R.id.sp_ResidenceType) Spinner sp_ResidenceType;
    @BindView(R.id.sp_Nation) Spinner sp_Nation;
    @BindView(R.id.sp_PoliticalStatus) Spinner sp_PoliticalStatus;//政治面貌
    @BindView(R.id.sp_Marriage) Spinner sp_Marriage;
    @BindView(R.id.tv_HouseHoldPlace) TextView tv_HouseHoldPlace;//户籍地
    @BindView(R.id.tv_BirthPlace) TextView tv_BirthPlace;//籍贯
    @BindView(R.id.tv_NowAddress) TextView tv_NowAddress;//现在地
    @BindView(R.id.et_HouseholdAddress) EditText et_HouseholdAddress;//户籍详址
    @BindView(R.id.rg_NowAddress) RadioGroup rg_NowAddress;
    @BindView(R.id.rbt_Yes) RadioButton rbt_Yes;//有无现住门(楼)详址
    @BindView(R.id.rbt_No) RadioButton rbt_No;
    @BindView(R.id.tv_NowHouseTitle) TextView tv_NowHouseTitle;//现住详址
    @BindView(R.id.et_NowHouseAddress) EditText et_NowHouseAddress;//现住详址
    @BindView(R.id.et_OldName) EditText et_OldName;
    @BindView(R.id.et_Phone) EditText et_Phone;
    @BindView(R.id.et_Telephone) EditText et_Telephone;
    @BindView(R.id.tv_Education) TextView tv_Education;
    @BindView(R.id.sp_ProfessionType) Spinner sp_ProfessionType;
    @BindView(R.id.et_Profession) EditText et_Profession;//职业
    @BindView(R.id.sp_Religion) Spinner sp_Religion;//宗教信仰
    @BindView(R.id.et_Service) EditText et_Service;//服务处所
    private PopulationDetailBean detailBean;
    /**0:户籍地 1：籍贯 2：现在地*/
    private int addressType;
    private SparseArray householdId,birthPlacrId,nowAddressId;
    private String path;
    private EducationBean.SchoolingsBean schoolingsBean;
    private OptionsPickerView pvOptions;
    private CheckMessagePest messagePest;
    private boolean isEdit;
    private ArrayList<ProvinceBean> provinceList;
    private ArrayList<List<ProvinceBean>> cityList;
    private ArrayList<List<List<ProvinceBean>>> districtList;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_basic_infor_edit,container,false);
        ButterKnife.bind(this,view);
        detailBean= (PopulationDetailBean) getArguments().getSerializable("PopulationDetailBean");
        isEdit=getArguments().getBoolean("isEdit");
        initData();
        showViews();
        return view;
    }

    private void initData() {
        new ProvinceUtils().initData(getActivity(), new ProvinceUtils.AdapterCallback() {
            @Override
            public void getData(ArrayList<ProvinceBean> provinceList, ArrayList<List<ProvinceBean>> cityList,
                                ArrayList<List<List<ProvinceBean>>> districtList) {
                BasicInforEditFragment.this.provinceList=provinceList;
                BasicInforEditFragment.this.cityList=cityList;
                BasicInforEditFragment.this.districtList=districtList;
                showCity();
            }
        });
        PublicListPest publicListPest=new PublicListPest(this);
        publicListPest.getPublicList("性别");
        publicListPest.getPublicList("民族");
        publicListPest.getPublicList("政治面貌");
        publicListPest.getPublicList("婚姻状况");
        publicListPest.getPublicList("职业");
        publicListPest.getPublicList("宗教信仰");
        publicListPest.getPublicList("户口类别");
        imv_Head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelector.create(BasicInforEditFragment.this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .withAspectRatio(1,1)
                        .enableCrop(true)
                        .compress(true)
                        .compressGrade(Luban.CUSTOM_GEAR)
                        .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });

        rg_NowAddress.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId==R.id.rbt_Yes){
                    tv_NowHouseTitle.setText("现住门(楼)详址");
                }else if(checkedId==R.id.rbt_No){
                    tv_NowHouseTitle.setText("无住房原因");
                }
            }
        });
    }


    @OnClick({R.id.tv_Data,R.id.tv_Education,R.id.tv_HouseHoldPlace,R.id.tv_BirthPlace,R.id.tv_NowAddress})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.tv_Data:
                BaseUtil.createDataPop(getActivity(),tv_Data);
                break;
            case R.id.tv_Education:
                startActivityForResult(new Intent(getActivity(),EducationActivity.class),4447);
                break;
            case R.id.tv_HouseHoldPlace:
                if (pvOptions!=null){
                    pvOptions.show();
                    addressType=0;
                }
                break;
            case R.id.tv_BirthPlace:
                if (pvOptions!=null){
                    pvOptions.show();
                    addressType=1;
                }
                break;
            case R.id.tv_NowAddress:
                if (pvOptions!=null){
                    pvOptions.show();
                    addressType=2;
                }
                break;

        }
    }

    private void showCity() {
        if (pvOptions==null) {
            pvOptions = new OptionsPickerView.Builder(getActivity(), new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3, View v) {
                    // 返回的分别是三个级别的选中位置
                    String tx = provinceList.get(options1).getPickerViewText()+"-"+
                            cityList.get(options1).get(option2).getPickerViewText()+"-"+
                            districtList.get(options1).get(option2).get(options3).getPickerViewText();
                    String provinceId=provinceList.get(options1).getId();
                    String cityId=cityList.get(options1).get(option2).getId();
                    String districtId=districtList.get(options1).get(option2).get(options3).getId();
                    if (addressType==0){
                        tv_HouseHoldPlace.setText(tx);
                        if (householdId==null){
                            householdId=new SparseArray();
                        }
                        householdId.clear();
                        idPut(householdId,provinceId,cityId,districtId);
                    }
                    if (addressType==1){
                        tv_BirthPlace.setText(tx);
                        if (birthPlacrId==null){
                            birthPlacrId=new SparseArray();
                        }
                        birthPlacrId.clear();
                        idPut(birthPlacrId,provinceId,cityId,districtId);
                    }

                    if (addressType==2){
                        tv_NowAddress.setText(tx);
                        if (nowAddressId==null){
                            nowAddressId=new SparseArray();
                        }
                        nowAddressId.clear();
                        idPut(nowAddressId,provinceId,cityId,districtId);
                    }
                }
            }).setTitleText("地区选择")
                    .setDividerColor(Color.RED)
                    .setTextColorCenter(Color.RED) //设置选中项文字颜色
                    .setContentTextSize(15)
                    .build();
            pvOptions.setPicker(provinceList, cityList, districtList);
        }
    }


    public boolean submit(){
        try {

            String idCardNum=et_IDCard.getText().toString().trim();
            if (idCardNum.length()!=18){
                ToastUtils.showToast(getActivity(),"身份证号码有误");
                et_IDCard.setError("身份证号码有误");
                return false;
            }
            String name=et_Name.getText().toString().trim();
            if (name.length()<2||name.length()>30){
                ToastUtils.showToast(getActivity(),"姓名不符合要求");
                et_Name.setError("姓名不符合要求");
                return false;
            }
            String birthday=tv_Data.getText().toString();
            if (BaseUtil.isEmpty(birthday)){
                ToastUtils.showToast(getActivity(),"请选择出生日期");
                return false;
            }
            String houseAddress=et_HouseholdAddress.getText().toString().trim();
            if (houseAddress.length()<1){
                ToastUtils.showToast(getActivity(),"户籍门楼详址不能为空");
                et_HouseholdAddress.setError("户籍门楼详址不能为空");
                return false;
            }
            String currentAddress=et_NowHouseAddress.getText().toString().trim();
            if (currentAddress.length()<1){
                if (rbt_Yes.isChecked()){
                    ToastUtils.showToast(getActivity(),"现住门楼详址不能为空");
                    et_NowHouseAddress.setError("现住门楼详址不能为空");
                }else {
                    ToastUtils.showToast(getActivity(),"无住房原因");
                    et_NowHouseAddress.setError("无住房原因");
                }
                return false;
            }
            String phone=et_Phone.getText().toString().trim();
            String tel=et_Telephone.getText().toString().trim();
            if (BaseUtil.isEmpty(phone)&&BaseUtil.isEmpty(tel)){
                et_Phone.setError("手机与号码至少输入一项");
                ToastUtils.showToast(getActivity(),"手机与号码至少输入一项");
                return false;
            }
            if (!BaseUtil.isEmpty(phone)&&!BaseUtil.isMobile(phone)){
                et_Phone.setError("请输入正确手机号格式");
                return false;
            }
            if (schoolingsBean==null){
                ToastUtils.showToast(getActivity(),"请选择学历");
                return false;
            }
            String profession=et_Profession.getText().toString();
            if (profession.length()>15||profession.length()<2){
                ToastUtils.showToast(getActivity(),"请重新填写 职业");
                et_Profession.setError("2~15个字");
                return false;
            }

            if (!BaseUtil.isEmpty(path)){
                detailBean.setImgUrl(path);
            }
            detailBean.setIdCardNo(idCardNum);
            detailBean.setName(name);
            GlobalBean sexBean= (GlobalBean) sp_Sex.getSelectedItem();
            if (sexBean==null){
                ToastUtils.showToast(getActivity(),"请选择性别");
                return false;
            }
            detailBean.setGender(sexBean);
            detailBean.setBirthday(birthday);
            GlobalBean residenceBean= (GlobalBean) sp_ResidenceType.getSelectedItem();
            if (residenceBean==null){
                ToastUtils.showToast(getActivity(),"请选择户口类型");
                return false;
            }
            detailBean.setResidenceType(residenceBean);
            GlobalBean nation=(GlobalBean)sp_Nation.getSelectedItem();
            if (nation==null){
                ToastUtils.showToast(getActivity(),"请选择民族");
                return false;
            }
            detailBean.setNation(nation);
            if (householdId==null){
                ToastUtils.showToast(getActivity(),"请选择户籍地");
                return false;
            }
            detailBean.setProvince((String) householdId.get(0));
            detailBean.setCity((String) householdId.get(1));
            detailBean.setDistrict((String) householdId.get(2));
            if (birthPlacrId==null){
                ToastUtils.showToast(getActivity(),"请选择籍贯");
                return false;
            }
            detailBean.setPlaceProvince((String) birthPlacrId.get(0));
            detailBean.setPlaceCity((String) birthPlacrId.get(1));
            detailBean.setPlaceDistrict((String) birthPlacrId.get(2));
            if (nowAddressId==null){
                ToastUtils.showToast(getActivity(),"请选现住地");
                return false;
            }
            detailBean.setPresentProvince((String) nowAddressId.get(0));
            detailBean.setPresentCity((String) nowAddressId.get(1));
            detailBean.setPresentDistrict((String) nowAddressId.get(2));
            detailBean.setNativePlaceAddress(houseAddress);
            if (rbt_Yes.isChecked()){
                detailBean.setIsHaveHouse(true);
                detailBean.setCurrentAddress(currentAddress);
            }else {
                detailBean.setIsHaveHouse(false);
                detailBean.setNoHouseReason(currentAddress);
            }
            GlobalBean personType= (GlobalBean) sp_PoliticalStatus.getSelectedItem();
            if (personType==null){
                ToastUtils.showToast(getActivity(),"请选择政治面貌");
                return false;
            }
            detailBean.setPoliticalBackground(personType);
            GlobalBean marriage= (GlobalBean) sp_Marriage.getSelectedItem();
            if (marriage==null){
                ToastUtils.showToast(getActivity(),"请选择婚姻状况");
                return false;
            }
            detailBean.setMaritalState(marriage);
            detailBean.setUsedName(et_OldName.getText().toString().trim());
            detailBean.setTelephone(et_Telephone.getText().toString().trim());
            detailBean.setMobileNumber(et_Phone.getText().toString().trim());
            detailBean.setSchoolStr(schoolingsBean.getName());
            detailBean.setSchoolVal(schoolingsBean.getValue());
            GlobalBean per= (GlobalBean) sp_ProfessionType.getSelectedItem();
            if (per==null){
                ToastUtils.showToast(getActivity(),"请选择职业类别");
                return false;
            }
            detailBean.setCareer(per);
            detailBean.setCareerText(profession);
            GlobalBean religion= (GlobalBean) sp_Religion.getSelectedItem();
            detailBean.setFaith(religion);
            detailBean.setWorkUnit(et_Service.getText().toString().trim());
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    private void showViews() {
        try {
            et_IDCard.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {}
                @Override
                public void afterTextChanged(Editable s) {
                    if (s.length()==18&&et_IDCard.isClickable()) {
                        tv_Data.setText(s.subSequence(6, 10) + "-" + s.subSequence(10, 12) + "-" + s.subSequence(12, 14));
                        if (messagePest == null) {
                            messagePest = new CheckMessagePest(BasicInforEditFragment.this);
                        }
                        LoadDialog.show(getActivity(),"检测身份证");
                        messagePest.checkHouseHold("hasDuplicatePopulation.action",s.toString(),"","","");
                    }
                }
            });

            if (isEdit){
                et_IDCard.setClickable(false);
                et_IDCard.setEnabled(false);
                et_IDCard.setText(detailBean.getIdCardNo());
                et_Name.setText(detailBean.getName());
                tv_Data.setText(detailBean.getBirthday());
                tv_HouseHoldPlace.setText(detailBean.getDomicilePlace());
                if (householdId==null){
                    householdId=new SparseArray();
                }
                householdId.clear();
                idPut( householdId, detailBean.getProvince(),detailBean.getCity(),detailBean.getDistrict());
                if (birthPlacrId==null){
                    birthPlacrId=new SparseArray();
                }
                birthPlacrId.clear();
                idPut(birthPlacrId, detailBean.getPlaceProvince(),detailBean.getPlaceCity(),
                        detailBean.getPlaceDistrict());
                if (nowAddressId==null){
                    nowAddressId=new SparseArray();
                }
                nowAddressId.clear();
                idPut( nowAddressId, detailBean.getPresentProvince(),detailBean.getPresentCity(),
                        detailBean.getPresentDistrict());
                tv_BirthPlace.setText(detailBean.getPlace());
                tv_NowAddress.setText(detailBean.getPresent());
                et_HouseholdAddress.setText(detailBean.getNativePlaceAddress());
                if (detailBean.isIsHaveHouse()){
                    rbt_Yes.setChecked(true);
                    tv_NowHouseTitle.setText("现住门(楼)详址");
                    et_NowHouseAddress.setText(detailBean.getCurrentAddress());
                }else {
                    rbt_No.setChecked(true);
                    tv_NowHouseTitle.setText("无住房原因");
                    et_NowHouseAddress.setText(detailBean.getNoHouseReason());
                }
                et_OldName.setText(detailBean.getUsedName());
                et_Phone.setText(detailBean.getMobileNumber());
                et_Telephone.setText(detailBean.getTelephone());
                et_Profession.setText(detailBean.getCareerText());
                if (!BaseUtil.isEmpty(detailBean.getSchoolVal())){
                    tv_Education.setText(detailBean.getSchoolStr());
                    schoolingsBean=new EducationBean.SchoolingsBean(detailBean.getSchoolStr(),
                            detailBean.getSchoolVal());
                }
                et_Service.setText(detailBean.getWorkUnit());
                path=ServiceFactory.NEW_API_BASE_URL+ File.separator+detailBean.getImgUrl();
                RequestOptions options = new RequestOptions()
                        .centerCrop()
                        .placeholder(R.mipmap.head_default)
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
                Glide.with(getActivity())
                        .load(path)
                        .apply(options)
                        .into(imv_Head);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void idPut(SparseArray array, String province, String city, String district) {
        array.put(0,province);
        array.put(1,city);
        array.put(2,district);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST://选图片
                    List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                    if (!picUrls.isEmpty()) {
                        path = picUrls.get(0).getCompressPath();
                        RequestOptions options = new RequestOptions()
                                .centerCrop()
                                .placeholder(R.mipmap.head_default);
                        Glide.with(getActivity())
                                .load(path)
                                .apply(options)
                                .into(imv_Head);
                    }
                    break;
                case 4447://学历
                    schoolingsBean= (EducationBean.SchoolingsBean)data.getSerializableExtra("SchoolingsBean");
                    tv_Education.setText(schoolingsBean.getName());
                    break;
            }
        }
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(getActivity());
        ToastUtils.showToast(getActivity(),message);
    }

    @Override
    public void getPublicList(PublicBean publicBean) {
        if ("性别".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getGender() != null) {
                id = detailBean.getGender().getId();
            }
            showSpinner(sp_Sex, publicBean.getDicts(),id);
        }
        if ("民族".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getNation() != null) {
                id = detailBean.getNation().getId();
            }
            showSpinner(sp_Nation, publicBean.getDicts(),id);
        }
        if ("政治面貌".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getPoliticalBackground() != null) {
                id = detailBean.getPoliticalBackground().getId();
            }
            showSpinner(sp_PoliticalStatus, publicBean.getDicts(),id);
        }
        if ("婚姻状况".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getMaritalState() != null) {
                id = detailBean.getMaritalState().getId();
            }
            showSpinner(sp_Marriage, publicBean.getDicts(),id);
        }

        if ("职业".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getCareer() != null) {
                id = detailBean.getCareer().getId();
            }
            showSpinner(sp_ProfessionType, publicBean.getDicts(),id);
        }
        if ("宗教信仰".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getFaith() != null) {
                id = detailBean.getFaith().getId();
            }
            showSpinner(sp_Religion, publicBean.getDicts(),id);
        }
        if ("户口类别".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getResidenceType() != null) {
                id = detailBean.getResidenceType().getId();
            }
            showSpinner(sp_ResidenceType, publicBean.getDicts(),id);
        }
    }

    private void showSpinner(Spinner spinner, List<GlobalBean> datas,String id) {
        SpinnerPubAdapter adapter=new SpinnerPubAdapter(getActivity(),R.layout.item_text,datas);
        spinner.setAdapter(adapter);
        if (!BaseUtil.isEmpty(id)){
            int count=datas.size();
            for (int i=0;i<count;i++){
                if (id.equals(datas.get(i).getId())){
                    spinner.setSelection(i);
                    break;
                }
            }
        }

    }

    @Override
    public void checkSuccess(Boolean result, String message) {
        LoadDialog.dismiss(getActivity());
        if (!result){
            et_IDCard.setError(message);
        }
    }
}
